---
import Icon from "../../lib/Icon.astro"
import FormatHTML from "../../lib/FormatHTML.astro"
import { createDocument } from "../../utils"
import {
    type Project as ProjectType,
    needsProjectPage,
} from "../../api/projects"
import { marked } from "marked"

export interface Props {
    project: ProjectType
}

const { project } = Astro.props
const {
    frontmatter: { link, title, links, color, time },
} = project

const html = await marked(project.rawContent())

const document = createDocument(html)

const isHTMLElement = (child: Node): child is HTMLElement =>
    child.nodeType !== 3

const Tizer = (document: HTMLElement) => {
    let result = ""
    for (const child of document.childNodes) {
        if (!isHTMLElement(child)) continue
        const tagName = child.tagName.toLocaleLowerCase()
        if (tagName === "hr") return result
        result += child.outerHTML
    }
    return result
}

const description = needsProjectPage(project) ? Tizer(document) : html
---

<div class="project" style={{ "--color": color }}>
    <div class="project__header">
        <div class="project__title">
            <h3>
                {title}
                <a
                    href={link}
                    target="blank"
                    class="project__link"
                    aria-label=`Перейти на ${title}`></a>
            </h3>
            {time && <div class="project__time">{time}</div>}
        </div>
        <ul class="links">
            {
                links.map(({ href, title, icon }) => (
                    <li>
                        <a
                            href={href}
                            target="blank"
                            class="link"
                            aria-label={title}
                        >
                            <Icon name={icon} />
                        </a>
                    </li>
                ))
            }
        </ul>
    </div>
    <div class="project__content">
        <FormatHTML html={description} />
    </div>
</div>

<style>
    .project h3 {
        margin: 0;
        position: relative;
        &:hover {
            color: var(--color, inherit);
        }
    }
    .project__link {
        position: absolute;
        inset: 0;
        outline-color: var(--color, currentColor);
    }
    .project__content :global(ul) {
        margin: 0;
    }
    .project__content :global(strong) {
        font-weight: normal;
        color: var(--title-color);
    }

    .project__header {
        display: flex;
        justify-content: space-between;
    }
    .links {
        margin: 0;
        padding: 0;
        list-style: none;
        display: flex;
        gap: 1em;
    }
    @media screen {
        .link {
            filter: grayscale(100%);
            &:hover,
            &:focus-within {
                filter: grayscale(0);
            }
        }
    }
</style>
